<?php

namespace app\api\service;

use app\model\Money;
use app\model\Records;
use app\model\VideoDetails;
use app\model\BingeWatch;
use app\model\Videos;
use think\facade\Cache;
use think\facade\Db;
use app\model\KeywordReply;
use app\model\User;
use app\model\WatchPayRecord;
use app\model\PayRecord;
use think\facade\Log;

class RecordService
{
    private $recordsModel;
    private $videoDetailsModel;
    private $bingeWatchModel;
    private $videoModel;
    private $keywordReplyModel;
    private $userModel;
    private $watchPayRecordModel;
    private $payRecordModel;

    public function __construct(Records $recordsModel, VideoDetails $videoDetailsModel, BingeWatch $bingeWatchModel, Videos $videoModel, KeywordReply $keywordReplyModel, User $userModel, WatchPayRecord $watchPayRecordModel, PayRecord $payRecordModel)
    {
        $this->recordsModel = $recordsModel;
        $this->videoDetailsModel = $videoDetailsModel;
        $this->bingeWatchModel = $bingeWatchModel;
        $this->videoModel = $videoModel;
        $this->keywordReplyModel = $keywordReplyModel;
        $this->userModel = $userModel;
        $this->watchPayRecordModel = $watchPayRecordModel;
        $this->payRecordModel = $payRecordModel;
    }

    /**
     * 获取历史记录
     * 
     * @dateTime 2022/09/03
     * @author zhixiang0215@126.com
     * @param int uid
     * @return array
     */
    public function getHistoryList($params, $uid)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 30;

        // 获取历史记录
        $data = $this->recordsModel->getDataByUid($uid, $page, $limit, 'id, video_detail_id, video_id','updated_at desc');
        if ($data['total'] == 0) {
            return [];
        }
        $videoIds = array_column($data['data'], 'video_id');

        $videoData = $this->videoModel->getDataByIds($videoIds, 'id, name, label, title_label, cover_img, is_free, synopsis, status, drama_id');
        $videoResult = array_column($videoData, NULL, 'id');

        $countData = $this->videoDetailsModel->getInfoByVideoIds($videoIds, 'id, video_id, sort');
        $countResult = [];
        foreach ($countData as $item) {
            $countResult[$item['video_id']][] = $item['sort'];
        }

        $sortData = array_column($countData, 'sort', 'id');

        // 是否追剧
        // $bingeWatchData = $this->bingeWatchModel->getDataByWhere(['uid' => $uid, 'video_id' => $videoIds], 'id, video_id, sort');
        // $bingeWatchResult = array_column($bingeWatchData, NULL, 'video_id');

        foreach ($data['data'] as $index => $item) {
            if (empty($videoResult[$item['video_id']])) {
                unset($data['data'][$index]);
                continue;
            }
            $data['data'][$index]['name'] = empty($videoResult[$item['video_id']]) ? '' : $videoResult[$item['video_id']]['name'];
            $data['data'][$index]['cover_img'] = empty($videoResult[$item['video_id']]) ? '' : $videoResult[$item['video_id']]['cover_img'];
            $data['data'][$index]['count'] = empty($countResult[$item['video_id']]) ? 0 : count($countResult[$item['video_id']]);
            $data['data'][$index]['status'] = empty($videoResult[$item['video_id']]) ? 0 : $videoResult[$item['video_id']]['status'];

            $data['data'][$index]['sort'] = empty($sortData[$item['video_detail_id']]) ? 1 : $sortData[$item['video_detail_id']];
            // $data['data'][$index]['is_binge_watch'] = empty($bingeWatchResult[$item['video_id']]) ? 0 : 1;
            $data['data'][$index]['drama_id'] = $videoResult[$item['video_id']]['drama_id'] ?? '';
        }

        $data['data'] = array_values($data['data']);
        return $data;
    }

    /**
     * 追剧
     * 
     * @dateTime 2022/09/03
     * @author zhixiang0215@126.com
     * @param array params
     * @param int uid
     * @return array
     */
    public function getBingeWatchList(array $params, int $uid)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 30;

        $data = $this->bingeWatchModel->getDataByUid($uid, $page, $limit, 'id, video_detail_id, video_id, sort');

        if ($data['total'] == 0) {
            return [];
        }
        $videoIds = array_column($data['data'], 'video_id');

        $videoData = $this->videoModel->getDataByIds($videoIds, 'id, name, cover_img, drama_id');
        $videoResult = array_column($videoData, NULL, 'id');

        $countData = $this->videoDetailsModel->getInfoByVideoIds($videoIds, 'id, video_id');

        $countResult = [];
        foreach ($countData as $item) {
            $countResult[$item['video_id']][] = $item['id'];
        }

        foreach ($data['data'] as $index => $item) {
            $data['data'][$index]['name'] = empty($videoResult[$item['video_id']]) ? '' : $videoResult[$item['video_id']]['name'];
            $data['data'][$index]['cover_img'] = empty($videoResult[$item['video_id']]) ? '' : $videoResult[$item['video_id']]['cover_img'];
            $data['data'][$index]['count'] = empty($countResult[$item['video_id']]) ? 0 : count($countResult[$item['video_id']]);
            $data['data'][$index]['drama_id'] = $videoResult[$item['video_id']]['drama_id'] ?? '';
        }
        return $data;
    }

    /**
     * 添加/修改观看记录
     * 
     * @dateTime 2022/09/05
     * @author zhixiang0215@126.com
     * @param int videoDetailId
     * @param int uid
     * @return bool
     */
    public function editRecord(int $videoDetailId, int $uid)
    {
        $recordAddSwitch = config('trace.api_record_add_switch');
        
        if (!$recordAddSwitch){
            return true;
        } 

        $redisCacheSwitch = config('trace.redis_cache_switch');
        try {
            //code...
            $data = $this->videoDetailsModel->getInfoById($videoDetailId, 'video_id, sort');
            if (!$data){
                return false;
            } 

            // 播放次数加1
            //$this->videoModel->where(['id' => $data['video_id']])->inc('frequency', 1)->update();
            //$this->videoDetailsModel->where(['id' => $videoDetailId])->inc('frequency', 1)->update();

            //播放统计相关改redis计数
            if ($redisCacheSwitch) {
                $redis = Cache::store('redis')->handler();
                $redis->select(2);
                $videoKey = config('redis_key.video_statistic_count_key');
                $videoDetailKey = config('redis_key.video_detail_statistic_count_key').$data['video_id'];
                $redis->hIncrBy($videoKey, 'frequency_'.$data['video_id'], 1);
                $redis->hIncrBy($videoDetailKey, 'frequency_'.$videoDetailId, 1);
            }

            $recordData = $this->recordsModel->getInfoByWhere(['uid' => $uid, 'video_id' => $data['video_id']], 'id, video_detail_id');

            $saveData = [
                'uid' => $uid,
                'video_detail_id' => $videoDetailId,
                'video_id' => $data['video_id'],
                'updated_at' => time()
            ];

            if ($recordData) {
                // 修改
                $saveData['id'] = $recordData['id'];
                // 剧集观看人数加1
                if ($videoDetailId != $recordData['video_detail_id']) {
                    //$this->videoDetailsModel->where(['id' => $videoDetailId])->inc('number', 1)->update();
                    //$this->videoDetailsModel->where(['id' => $videoDetailId])->inc('today_number', 1)->update();

                    if ($redisCacheSwitch) {
                        $redis->hIncrBy($videoDetailKey, 'number_'.$videoDetailId, 1);
                        $redis->hIncrBy($videoDetailKey, 'today_number_'.$videoDetailId, 1);
                    }
                }
            } else {
                // 新增
                $saveData['created_at'] = time();
                // 播放人数加1
                //$this->videoModel->where(['id' => $data['video_id']])->inc('number', 1)->update();
                //$this->videoDetailsModel->where(['id' => $videoDetailId])->inc('number', 1)->update();
                //$this->videoDetailsModel->where(['id' => $videoDetailId])->inc('today_number', 1)->update();

                if ($redisCacheSwitch) {
                    $redis->hIncrBy($videoKey, 'number_'.$data['video_id'], 1);
                    $redis->hIncrBy($videoDetailKey, 'number_'.$videoDetailId, 1);
                    $redis->hIncrBy($videoDetailKey, 'today_number_'.$videoDetailId, 1);
                }

                // 有内推id keyword_reply表watch_num字段加1
                $userInfo = $this->userModel->getInfoById($uid, 'interpolate_id');
                if (!empty($userInfo['interpolate_id'])) {
                    $this->keywordReplyModel->where(['id' => $userInfo['interpolate_id']])->inc('watch_num', 1)->update();
                }
            }

            $id = $this->recordsModel->edit($saveData);

            // 修改追剧到多少集的记录
            $bingeWatchData = $this->bingeWatchModel->getInfo(['video_id' => $data['video_id'], 'uid' => $uid], 'id');
            if ($bingeWatchData) {
                $this->bingeWatchModel->edit([
                    'id' => $bingeWatchData['id'],
                    'video_detail_id' => $videoDetailId,
                    'sort' => $data['sort'],
                    'updated_at' => time()
                ]);
            }

            return $id;
        } catch (\Exception $e) {
            //throw $th;
            return false;
        }
    }

    /**
     * 添加/取消追剧记录
     * 
     * @dateTime 2022/09/05
     * @author zhixiang0215@126.com
     * @param array params
     * @param int uid
     * @param int type 1添加 2取消
     * @return bool
     */
    public function editBingeWatch(array $params, int $uid, int $type = 1)
    {
        $bingeWatchData = $this->bingeWatchModel->getInfo(['video_id' => $params['video_id'], 'uid' => $uid], 'id');

        if ($type == 1) {

            $saveData = [
                'uid' => $uid,
                'video_detail_id' => $params['video_detail_id'],
                'video_id' => $params['video_id'],
                'sort' => $params['sort'],
                'update_time' => time()
            ];
            if ($bingeWatchData) {
                // 修改
                $saveData['id'] = $bingeWatchData['id'];
            } else {
                // 新增
                $saveData['created_at'] = time();
            }
            $id = $this->bingeWatchModel->edit($saveData);
            return $id;
        } else {
            // 取消追剧
            if (!$bingeWatchData) {
                return false;
            }
            return $this->bingeWatchModel->destroy($bingeWatchData['id']);
        }
    }

    // 获取用户充值记录
    public function getUserRechangeRecord($params, $uid)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $data = $this->payRecordModel->getPagingDataByWhere(['uid' => $uid, 'status' => 1], $page, $limit, 'id, name, type, total_fee, number, pay_time, video_id');

        if ($data['data']) {
            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['pay_time'] = date('Y-m-d H:i:s', $value['pay_time']);
                $data['data'][$key]['name'] = Money::getTypeText($value);
                $data['data'][$key]['pay_text'] = PayRecord::getPayTextForApplet($value);
                $data['data'][$key]['pay_type'] = PayRecord::getPayTypeForApplet($value);
            }
        }
        return $data;
    }

    // 获取用户消费记录
    public function getWatchPayRecord($params, $uid)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $data = $this->watchPayRecordModel->getPagingDataByWhere(['uid' => $uid], $page, $limit, 'id, video_id, video_detail_id, money, created_at');

        if ($data['data']) {
            $videoDetailIds = $videoIds = [];
            foreach ($data['data'] as $key => $value) {
                $videoIds[] = $value['video_id'];
                $videoDetailIds[] = $value['video_detail_id'];
            }

            $videoData = $this->videoModel->getDataByIds($videoIds, 'id, name');
            $videoDetailData = $this->videoDetailsModel->getInfoByIds($videoDetailIds, 'id, sort');

            $videoResult = array_column($videoData, 'name', 'id');
            $videoDetailResult = array_column($videoDetailData, 'sort', 'id');

            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['video_name'] = empty($videoResult[$value['video_id']]) ? '' : $videoResult[$value['video_id']];
                $data['data'][$key]['video_sort'] = empty($videoDetailResult[$value['video_detail_id']]) ? '' : $videoDetailResult[$value['video_detail_id']];
                $data['data'][$key]['created_at'] = date('Y-m-d H:i:s', $value['created_at']);
            }
        }
        return $data;
    }
    /**
     * 查询当前支付订单号
     *
     * @param [type] $params
     * @param [type] $uid
     * @return void
     */
    public function PayOrderStatus($params, $uid)
    {
        $order_no=$params['order_no']??'';
        if(empty($order_no)){
            return ['status'=>0,'msg'=> '参数错误'];
        }
        //防止支付订单未成功回调，进行十次循环，大概5秒
        $pay=$this->payRecordModel->getDataByWhere(['order_no'=>$order_no], 'id,status');
        if(empty($pay)||$pay['status']==0){
            return ['status'=> 0,'msg'=> '未成功回调'];
        }else{
            return ['status'=> 1,'msg'=> '已成功'];
        }
    }
}